<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xmlns:fb="https://www.facebook.com/2008/fbml" xmlns:og="https://ogp.me/ns#" xml:lang="en">
  <head>
    <?php include_http_metas() ?>
    <?php include_stylesheets() ?>
    <?php include_javascripts() ?>
    <?php include_title() ?>
  </head>
  <body>
    <div id="fb-root"></div>
    <script>
<!--
try {
    if (document.location.href == top.location.href)
        top.location.href = '<?php echo UrlFunctions::genFbUrl('@homepage', true) ?>'+document.location.href.replace(/https?:\/\/[^/]*\/?/, '');
} catch (e) {}

window.fbAsyncInit = function() {
    FB.init({
        appId: '<?php echo App::getCurrentApiId() ?>',
        status: true,
        cookie: true,
        xfbml: true,
        channelUrl: '<?php echo url_for('@js_sdk_channel', true) ?>',
        oauth: true
        });
    FB.Canvas.setAutoGrow();
<?php /*
    The statuses objects returned in the responses from the following events are as follow:
    auth.authResponseChange: - connected     => authorized user
                        - notConnected  => logged in but not authorized
                        - unknown       => not logged into Facebook
    auth.statusChange:  - connected     => authorized user
                        - notConnected  => logged in but not authorized
                        - notLogged     => not logged into Facebook
    The first tests show strange behavior with status not always matching the actual one,
    I've seen a authResponseChange.status == 'connected' when I actually unlogged from FB in another tab...
    Or no authResponseChange at all in some cases.
*/ ?>
    FB.Event.subscribe('auth.authResponseChange', function(response) {
        // FIXME: does not work, generates "FB.getLoginStatus() called before calling FB.init()." error, see FS#12747
        // fss.refreshCookie();
    });

    $(document).ready(function() {
        fss._onReady();
        FB.getLoginStatus(fss._onLoginReady);
        FB.Canvas.setDoneLoading();
    });
};

(function() {
    var e = document.createElement('script'); e.async = true;
<?php
    if ($sf_user->getFbUser())
        $locale = sfConfig::get('fb_js_sdk_locales_'.$sf_user->getFbUser()->locale, 'en_US');
    else
        $locale = sfConfig::get('fb_js_sdk_locales_default');
?>
    <?php /* '?r=0' added to force cache clear, see FS#11489 */ ?>
    e.src = document.location.protocol+'//connect.facebook.net/<?php echo $locale ?>/all.js?r=1';
    document.getElementById('fb-root').appendChild(e);
}());


<?php // {{{ fss.View ?>

fss.View = {
    _anchor_el: null,
    _top: null
}

fss.View.anchor = function (el)
{
    if (el !== undefined) {
        fss.View._anchor_el = el;
        fss.View._top = null;
    }
    return fss.View._anchor_el;
}

<?php /*
Compute the position of an element (e.g. a dialog box) of given height.
  - If the function was already called before, return the cached value.
    This ensures that a series of dialogs will be aligned on top.
  - Align the bottom of the element on the anchor element if present.
  - Put the top of the element in the first 150px of the page otherwise.

Re FS#11407
*/ ?>
fss.View.top = function (height)
{
    if (fss.View._top !== null)
        return fss.View._top;

    if (fss.View.anchor()) {
        var top = $(fss.View.anchor()).offset().top - height;
        if (top < 0)
            top = 0;
        fss.View._top = top;
    } else {
        fss.View._top = 0;
    }
    return fss.View._top;
}

<?php /*
Scroll the FB page to the top of the page
*/ ?>
fss.View.reset = function ()
{
    document.getElementById('fb-root').scrollIntoView(true);
    fss.View.anchor(null);
}

<?php // }}} ?>

fss.showContextDialog = function(context, message)
{
    new fss.Dialog({
        context: context,
        message: message,
        confirm: <?php echo json_encode(__('OK')) ?>
    });
}

fss._ready = $([]);

fss._onReady = function ()
{
    fss.ready = function(f) { f(); };
    fss._ready.each(function () { this(); });
    fss._ready = null;
}

fss.ready = function (f)
{
    fss._ready.push(f);
}

fss._loginReady = $([]);

fss._onLoginReady = function (response)
{
    fss.loginReady = function(f) { f(); };
    fss._loginReady.each(function () { this(response); });
    fss._loginReady = null;
}

fss.loginReady = function (f)
{
    fss._loginReady.push(f);
}



fss.updateUserInfo = function(response)
{
    $.post('<?php echo url_for('@update_user_info') ?>', {
        src: (response ? 'perms' : 'load')
    }, function (data) {
        if (!response && data.status && data.status == 'missing_perms') {
            fss.requestCandidatePermissions(fss.updateUserInfo,data.perms);
        }
    }, 'json');
}

<?php /*
checkPermission calls callback(true) if the user/page identified by the uid has
all the permissions in permission_list, callback(false) otherwise.

permission_list is a comma-separated list of permissions, e.g. 'email,publish_stream'.
*/ ?>
fss.checkPermission = function(uid, permission_list, callback, is_retry)
{
    FB.api({
        method: 'fql.query',
        query: 'SELECT '+permission_list+' FROM permissions WHERE uid='+uid
    }, function (response) {
        if (response.error_code && !is_retry) {
            fss.refreshCookie();
            return fss.checkPermission(uid, permission_list, callback, true);
        } else {
            if (!response[0])
                return callback(false);
            for (p in response[0])
                if (response[0][p] != '1')
                    return callback(false);
            return callback(true);
        }
    });
}

fss.requestPagePublishPermission = function(callback,noCheck)
{
<?php if ($sf_user->getUid()): ?>
    var perms = 'publish_stream,manage_pages';
    if (noCheck) {
        fss.requestCandidatePermissions(callback, perms);
        return;
    }
    fss.checkPermission(<?php echo $sf_user->getUid() ?>,
        perms,
        function (enabled) {
        if (!enabled)
            fss.requestCandidatePermissions(callback, perms);
        else if (callback)
            callback();
    });
<?php else: ?>
    callback();
<?php endif ?>
}

<?php /*
requestCandidatePermissions requests permissions for alerts and smart engines, then
calls callback(permission_list) if a permission_list was asked and accepted,
callback(true) if 'auth_only' was asked and accepted, callback(false) otherwise.

The alerts_permissions check is done on load inside alertScript to avoid latency later.
*/ ?>
fss.requestCandidatePermissions = function(callback, permission_list)
{
    FB.login(function (response) {
        if (response.perms)
            callback(response.perms);
        else if (response.authResponse)
            callback(true);
        else
            callback(false);
    }, {
        scope: permission_list
    });
}

<?php
    // We call this function in fbAsyncInit because we may need to show the
    // permission dialog in order to be able to get an email from the api
    if ($sf_user->getFbUser() && $sf_user->getFbUser()->isMissingField())
        echo "fss.ready(function () { fss.updateUserInfo() });\n";
?>

fss.refreshCookie = function()
{
    FB.getLoginStatus(null, true); <?php // force refresh (see auth.js line 348) ?>
}

fss.stopEvent = function (event)
{
    if (event && event.stopPropagation){
        event.stopPropagation();
    } else if(window.event) {
        window.event.cancelBubble=true;
    }
}

$('body').ajaxError(function (event, XMLHttpRequest, ajaxOptions, thrownError) {
    if (XMLHttpRequest.status == 0 || XMLHttpRequest.status == 200) {
        <?php /* Silently ignore aborted requests and 200 errors */ ?>
        try { console.log('Ajax error '+XMLHttpRequest.status); } catch (e) {}
    } else if (XMLHttpRequest.status == 403) {
        new fss.Dialog({
            title: <?php echo json_encode(__('Session expired')) ?>,
            message: <?php echo json_encode(__('Your session expired, please try again.')) ?>,
            confirm: <?php echo json_encode(__('OK')) ?>,
            onconfirm: function () {
                document.location.href = document.location.href.replace(/#.*/, '');
                fss.Dialog.closeAll();
            }
        });
    } else {
        return;
        new fss.Dialog({
            title: <?php echo json_encode(__('Application Error')) ?>,
            message: <?php echo json_encode(__('An error occured, please try again later (Error {error_code}).')) ?>.replace('{error_code}', XMLHttpRequest.status),
            confirm: <?php echo json_encode(__('Close')) ?>,
            onconfirm: function () {
                fss.Dialog.closeAll();
            }
        });
    }
});



-->
    </script>
